﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.Linq;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;

namespace Mota.XMLControls
{
    public class MyDxCheckedComboBox : CheckedComboBoxEdit
    {
        public event PropertyChangedEventHandler ItemsChanged;
        public MyDxCheckedComboBox()
            : base()
        {
            this.EditValueChanged += MyDxCheckedComboBox_EditValueChanged;
        }

        void MyDxCheckedComboBox_EditValueChanged(object sender, EventArgs e)
        {
            if (this.Properties.DataSource != null)
            {
                this.OnItemsChanged(null);
            }
        }

        public IEnumerable<KeyValuePair<string,bool>> GetItemsStates()
        {
            var items = this.Properties.Items;
            foreach (CheckedListBoxItem item in items)
            {
                yield return new KeyValuePair<string, bool>(item.Value.ToString(),
                                                                item.CheckState==CheckState.Checked);
            }
        }

        //Makes this property bindable.
        [Bindable(true)]
        public string XmlItems
        {
            get
            {

                XElement items = new XElement("Items",
                        GetItemsStates().Select(el=>new XElement("Item",
                            new XAttribute("Value",el.Key)){Value = el.Value.ToString().ToLower()})
                    );
                return items.ToString();
            }
            set
            {
                this.SetEditValue(String.Empty);
                if (!String.IsNullOrEmpty(value))
                {
                    XElement items = XElement.Parse(value);
                    IEnumerable<string> xmlItems = from item in items.Elements("Item")
                                                   let itAttrValue = item.Attribute("Value").Value
                                                   where Convert.ToBoolean(item.Value)==true 
                                                   select itAttrValue;
                        
                    this.SetEditValue(String.Join(this.Properties.SeparatorChar.ToString(),xmlItems));
                }
            }
        }
        public void OnItemsChanged(PropertyChangedEventArgs e)
        {
            //Raise the event
            if (ItemsChanged != null)
                ItemsChanged(this, e);
        }
    }
}
